//
//  QHTools.m
//  FuturesNews
//
//  Created by 张伟 on 2021/3/22.
//

#import "ZWTools.h"
#import <LocalAuthentication/LocalAuthentication.h>

@implementation ZWTools
+ (UIViewController *)currentTopViewController {
    UIViewController* viewController = WINDOW.rootViewController;
    return [self findBestViewController:viewController];
}

+ (UIViewController *)findBestViewController:(UIViewController*)vc {
    if (vc.presentedViewController) {
        // Return presented view controller
        return [self findBestViewController:vc.presentedViewController];
    } else if ([vc isKindOfClass:[UISplitViewController class]]) {
        // Return right hand side
        UISplitViewController* svc = (UISplitViewController*) vc;
        if (svc.viewControllers.count > 0)
            return [self findBestViewController:svc.viewControllers.lastObject];
        else
            return vc;
    } else if ([vc isKindOfClass:[UINavigationController class]]) {
        // Return top view
        UINavigationController* svc = (UINavigationController*) vc;
        if (svc.viewControllers.count > 0)
            return [self findBestViewController:svc.visibleViewController];
        else
            return vc;
    } else if ([vc isKindOfClass:[UITabBarController class]]) {
        // Return visible view
        UITabBarController* svc = (UITabBarController*) vc;
        if (svc.viewControllers.count > 0)
            return [self findBestViewController:svc.selectedViewController];
        else
            return vc;
    } else {
        // Unknown view controller type, return last child view controller
        return vc;
    }
}

/// 打电话
/// @param phoneNumber 电话号码
+ (void)phoneCall:(NSString *)phoneNumber{
//    NSString * string = [NSString stringWithFormat:@"tel://%@",phoneNumber];
//    NSURL * url = [NSURL URLWithString:string];
//    if ([APP canOpenURL:url]) {
//        [APP openURL:url options:@{} completionHandler:nil];
//    }
}

/// 在App Store打开APP
/// @param appId APPID
+(void)commentAppWithAppidId:(NSInteger)appId{
//    NSString * str = [NSString stringWithFormat:@"itms-apps://itunes.apple.com/cn/app/id%ld?mt=8&action=write-review",appId];
//    NSURL * url = [NSURL URLWithString:str];
//    if ([APP canOpenURL:url]) {
//        [APP openURL:url options:@{} completionHandler:nil];
//    }
}

/// 更新APP
/// @param appId APPID
+(void)updateAppWithAppId:(NSInteger)appId{
//    NSString * str = [NSString stringWithFormat:@"https://itunes.apple.com/cn/app/id%ld?mt=8",appId];
//    NSURL * url = [NSURL URLWithString:str];
//    if ([APP canOpenURL:url]) {
//        [APP openURL:url options:@{} completionHandler:nil];
//    }
}

+ (void)shareApplicationWithAppId:(NSString *)appId{
    NSString * str = [NSString stringWithFormat:@"itms-apps://itunes.apple.com/cn/app/id%@?mt=8&action=write-review",appId];
    NSString *textToShare = @"分享应用";
    NSURL *urlToShare = [NSURL URLWithString:str];
    NSArray *activityItems = @[textToShare, urlToShare];
    UIActivityViewController *activityVC = [[UIActivityViewController alloc] initWithActivityItems:activityItems applicationActivities:nil];
    activityVC.completionWithItemsHandler = ^(NSString *activityType,BOOL completed,NSArray *returnedItems,NSError *activityError) {
        if (completed) { // 确定分享
            [ZWHud showMessage:@"分享成功,感谢支持" finishHandle:nil];
        } else {
            [ZWHud showMessage:@"分享失败" finishHandle:nil];
        }
    };
    [ZWTools.currentTopViewController presentViewController:activityVC animated:YES completion:nil];
}


+ (void)cleanUserData {
    [NSUserDefaults.standardUserDefaults setValue:@"" forKey:accountKey];
    [NSUserDefaults.standardUserDefaults setValue:@"" forKey:passwordKey];
    [NSUserDefaults.standardUserDefaults synchronize];
    
    UserModel.shared.account = @"";
    UserModel.shared.password = @"";
    UserModel.shared.userId = 0;
    UserModel.shared.isLogin = false;
}


+ (void)authenticateUserWithCompletion:(AuthenticationCompletion)completion {
    LAContext *context = [[LAContext alloc] init];
    NSError *error = nil;
    
    // 检查设备是否支持生物识别
    if ([context canEvaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics error:&error]) {
        // 支持生物识别
        [context evaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics
                localizedReason:@"请使用指纹或面容识别进行身份验证"
                          reply:^(BOOL success, NSError * _Nullable error) {
            if (completion) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    completion(success, error);
                });
            }
        }];
    } else {
        // 不支持生物识别
        if (completion) {
            dispatch_async(dispatch_get_main_queue(), ^{
                completion(NO, error);
            });
        }
    }
}

@end
